const APIKEY = "f05e2916745a4ecf89eda51cf71eac19"; // 填入你申请的KEY
const LOCATION = "111.318065,23.470543"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    warningMessage: [{
        id: "10130060320240620145005229121784",
        sender: "梧州市气象台",
        pubTime: "2024-06-20T14:50+08:00",
        title: "梧州市气象台发布雷电黄色预警信号[III级/较重]",
        startTime: "2024-06-20T14:50+08:00",
        endTime: "2024-06-21T14:50+08:00",
        status: "active",
        level: "黄色",
        severity: "Moderate",
        severityColor: "Yellow",
        type: "1014",
        typeName: "雷电",
        urgency: "",
        certainty: "",
        text: "梧州市气象台2024年6月20日14时50分发布雷电黄色预警信号：目前雷雨云团正在靠近万秀区、长洲区、龙圩区，预计未来6小时万秀区、长洲区、龙圩区将出现雷电，并伴短时强降雨或大风，请防范。",
        related: ""
      },
      {
        id: "10130060320240620145005229121785",
        sender: "梧州市气象台",
        pubTime: "2024-06-21T10:30+08:00",
        title: "梧州市气象台发布高温橙色预警信号[II级/严重]",
        startTime: "2024-06-21T10:30+08:00",
        endTime: "2024-06-22T10:30+08:00",
        status: "active",
        level: "橙色",
        severity: "Severe",
        severityColor: "Orange",
        type: "1015",
        typeName: "高温",
        urgency: "",
        certainty: "",
        text: "梧州市气象台2024年6月21日10时30分发布高温橙色预警信号：预计未来24小时内，梧州市大部分地区气温将升至37℃以上，请注意防范。",
        related: ""
      },
      {
        id: "10130060320240620145005229121786",
        sender: "梧州市气象台",
        pubTime: "2024-06-21T14:00+08:00",
        title: "梧州市气象台发布暴雨红色预警信号[I级/特别严重]",
        startTime: "2024-06-21T14:00+08:00",
        endTime: "2024-06-22T14:00+08:00",
        status: "active",
        level: "红色",
        severity: "Extreme",
        severityColor: "Red",
        type: "1016",
        typeName: "暴雨",
        urgency: "",
        certainty: "",
        text: "梧州市气象台2024年6月21日14时00分发布暴雨红色预警信号：预计未来3小时内，梧州市部分地区将出现100毫米以上的降水，请注意防范。",
        related: ""
      },
      {
        id: "10130060320240620145005229121787",
        sender: "梧州市气象台",
        pubTime: "2024-06-22T08:00+08:00",
        title: "梧州市气象台发布大风蓝色预警信号[IV级/一般]",
        startTime: "2024-06-22T08:00+08:00",
        endTime: "2024-06-23T08:00+08:00",
        status: "active",
        level: "蓝色",
        severity: "Minor",
        severityColor: "Blue",
        type: "1017",
        typeName: "大风",
        urgency: "",
        certainty: "",
        text: "梧州市气象台2024年6月22日08时00分发布大风蓝色预警信号：预计未来12小时内，梧州市部分地区将出现6级以上大风，请注意防范。",
        related: ""
      },
      {
        id: "10130060320240620145005229121788",
        sender: "梧州市气象台",
        pubTime: "2024-06-22T12:00+08:00",
        title: "梧州市气象台发布霜冻黄色预警信号[III级/较重]",
        startTime: "2024-06-22T12:00+08:00",
        endTime: "2024-06-23T12:00+08:00",
        status: "active",
        level: "黄色",
        severity: "Moderate",
        severityColor: "Yellow",
        type: "1018",
        typeName: "霜冻",
        urgency: "",
        certainty: "",
        text: "梧州市气象台2024年6月22日12时00分发布霜冻黄色预警信号：预计未来24小时内，梧州市部分地区将出现霜冻天气，请注意防范。",
        related: ""
      }
    ],
    sunrise: "", //日出时间
    sunset: "", //日落时间
    currentTime: "",
    progress: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLocation();
  },

  /**
   * 更新日落日出时间进度
   */
  updateProgress: function () {
    const sunriseTime = this.data.sunrise.split(":");
    const sunsetTime = this.data.sunset.split(":");
    const now = new Date();

    const sunrise = new Date(now.getFullYear(), now.getMonth(), now.getDate(), sunriseTime[0], sunriseTime[1]);
    const sunset = new Date(now.getFullYear(), now.getMonth(), now.getDate(), sunsetTime[0], sunsetTime[1]);
    const currentTime = now.getTime();

    // 日落时间与日出时间的差值，总日照时间（毫秒数）
    const totalDaylight = sunset - sunrise;
    // 当前时间与日出时间的差值，从日出到现在的时间（毫秒数）
    const timeSinceSunrise = currentTime - sunrise;

    // 当前时间在日出到日落之间所占的百分比
    const progress = Math.min(Math.max((timeSinceSunrise / totalDaylight) * 100, 0), 100);

    this.setData({
      currentTime: now.toTimeString().split(" ")[0],
      progress: progress
    });
  },

  //选择定位
  selectLocation() {
    var that = this
    wx.chooseLocation({
      success(res) {
        //console.log(res)
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
      },
      fail() {
        wx.getLocation({
          type: 'gcj02',
          fail() {
            wx.showModal({
              title: '获取地图位置失败',
              content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
              success(mRes) {
                if (mRes.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] === true) {
                        that.selectLocation()
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    },
                    fail(err) {
                      console.log(err)
                      wx.showToast({
                        title: '唤起设置页失败，请手动打开',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  })
                }
              }
            })
          }
        })

      }
    })
  },

  /**
   * 获取定位
   */
  getLocation() {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        that.setData({
          location: res.longitude + "," + res.latitude
        });
        that.getWeather();
        that.getCityByLoaction();
        // 停止下拉刷新
        wx.stopPullDownRefresh();
      },
      fail(err) {
        wx.showModal({
          title: '获取定位信息失败',
          content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
          success(mRes) {
            if (mRes.confirm) {
              wx.openSetting({
                success: function (data) {
                  if (data.authSetting["scope.userLocation"] === true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.getLocation();
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    });
                    that.setData({
                      location: "116.41,39.92"
                    });
                    that.getWeather();
                    that.getCityByLoaction();
                    // 停止下拉刷新
                    wx.stopPullDownRefresh();
                  }
                },
                fail(err) {
                  console.log(err);
                  wx.showToast({
                    title: '唤起设置页失败，请手动打开',
                    icon: 'none',
                    duration: 1000
                  });
                  that.setData({
                    location: "116.41,39.92"
                  });
                  that.getWeather();
                  that.getCityByLoaction();
                  // 停止下拉刷新
                  wx.stopPullDownRefresh();
                }
              });
            } else if (mRes.cancel) {
              that.setData({
                location: "116.41,39.92"
              });
              that.getWeather();
              that.getCityByLoaction();
              // 停止下拉刷新
              wx.stopPullDownRefresh();
            }
          }
        });
      }
    });
  },


  /**
   * 根据坐标获取城市信息
   */
  getCityByLoaction() {
    var that = this
    wx.request({
      url: 'https://geoapi.qweather.com/v2/city/lookup?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        if (res.code == "200") {
          var data = res.location[0]
          that.setData({
            City: data.adm2,
            County: data.name
          })
        } else {
          wx.showToast({
            title: '获取城市信息失败',
            icon: 'none'
          })
        }

      }
    })
  },

  /**
   * 获取当前时间
   */
  getCurrentDate() {
    const date = new Date();

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}${month}${day}`;
  },

  /**
   * 获取天气
   */
  getWeather() {
    var that = this
    wx.showLoading({
      title: '加载中',
    });

    /**
     * 获取当前天气
     */
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/now?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data;
        //console.log(res)
        that.setData({
          now: res.now
        })
      }
    });

    /**
     * 获取预警信息
     */
    wx.request({
      url: 'https://devapi.qweather.com/v7/warning/now?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data;
        console.log(res);
        that.setData({
          warningMessage: res.warning
        });
      }
    });

    /**
     * 获取未来24小时天气
     */
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/24h?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        res.hourly.forEach(function (item) {
          item.time = that.formatTime(new Date(item.fxTime)).hourly
        })
        that.setData({
          hourly: res.hourly
        })
      }
    });

    /**
     * 获取日出日落时间
     */
    wx.request({
      url: 'https://devapi.qweather.com/v7/astronomy/sun',
      data: {
        key: APIKEY,
        location: that.data.location,
        date: that.getCurrentDate()
      },
      method: 'GET',
      success(result) {
        that.setData({
          sunrise: that.formatDateTime(result.data.sunrise).split(" ")[1],
          sunset: that.formatDateTime(result.data.sunset).split(" ")[1]
        });
        that.updateProgress();
        setInterval(that.updateProgress, 60000); // 每分钟更新一次进度条

        wx.hideLoading();
      }
    });
  },

  // 格式时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
    const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
    return {
      hourly: [hour, minute].map(this.formatNumber).join(":"),
      daily: [month, day].map(this.formatNumber).join("-"),
      dailyToString: isToday ? "今天" : weekArray[date.getDay()]
    }
  },
  formatDateTime(dateTimeString) {
    // 创建一个 Date 对象
    const date = new Date(dateTimeString);

    // 获取日期部分
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    // 获取时间部分
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    // 拼接成目标格式
    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}`;

    return formattedDateTime;
  },

  // 补零
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getLocation();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})